package com.yz.food.controller;

import com.yz.food.common.Const;
import com.yz.food.pojo.Cart;
import com.yz.food.pojo.Category;
import com.yz.food.pojo.User;
import com.yz.food.service.CartService;
import com.yz.food.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 跳转到购物车界面
     */
    @RequestMapping("page/cart")
    public String cartPage(HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return "loginOrRegister";
        }
        // 查询出购物车明细
        List<Cart> carts = cartService.getByEmail((user.getEmail()));
        modelMap.addAttribute("carts", carts);
        List<Category> categories = categoryService.getAll();
        modelMap.addAttribute("categories", categories);
        modelMap.addAttribute("totalPrice", totalPrice(carts));
        return "cart";
    }

    // 计算总价
    private double totalPrice(List<Cart> list) {
        double totalPrice = 0.0;
        for (Cart cart : list) {
            totalPrice += cart.getTotalPrice();
        }
        return totalPrice;
    }

    /**
     * 添加商品到购物车
     */
    @RequestMapping("cart/addCart")
    public String addCart(@RequestParam("foodId") Integer foodId,
                          @RequestParam(value = "quantity", defaultValue = "1") Integer quantity,
                          HttpServletRequest request, ModelMap modelMap) {
        User user = (User) request.getSession(true).getAttribute(Const.CURRENT_USER);
        if (user == null) {
            return "loginOrRegister";
        }
        int result = cartService.addCart(foodId, quantity, user.getEmail());
        if (result > 0) {
            // 查询出所有的购物车明细
            List<Cart> carts = cartService.getByEmail((user.getEmail()));
            modelMap.addAttribute("carts", carts);
            return "redirect: /page/cart";
        }
        return "404";
    }

    /**
     * 根据购物车id删除
     */
    @RequestMapping("cart/deleteById")
    public String deleteById(@RequestParam("cartId") Integer cartId) {
        int result = cartService.deleteById(cartId);
        if (result > 0) {
            return "redirect: /page/cart";
        }
        return "404";
    }
}
